package com.glory.brepda.activity.mfg;

import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.EquipMentEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.ToolEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ToolBindActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etToolID)
    FreeUI_ClearEditText etToolID;
    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvEqpWorkPosition)
    TextView tvEqpWorkPosition;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flPositionList)
    FrameLayout flPositionList;
    @BindView(R.id.tvPosition)
    TextView tvPosition;
    @BindView(R.id.ivPositionArrow)
    ImageView ivPositionArrow;

    // 治具标准寿命和治具已使用次数显示框
    @BindView(R.id.llToolLimitLife)
    LinearLayout llToolLimitLife;

    // 治具标准寿命
    @BindView(R.id.tvToolLimitLife)
    TextView tvToolLimitLife;

    @BindView(R.id.llToolCurrentCount)
    LinearLayout llToolCurrentCount;

    // 治具已使用次数
    @BindView(R.id.tvToolCurrentCount)
    TextView tvToolCurrentCount;

    private FreeUI_GeneralPop mPositionPop;
    private List<String> mPositionList;

    private String eqpRunningLot;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_tool_bind;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        mPositionList = new ArrayList<>();
        setMainLayout(llMain);

        // 触发点：计划扫描治具编号、设备编号和批次id都会触发查询治具信息
        // 方法里会自动校验这三个值有没有填写，都没有填写的话，不会触发接口请求
        initEdit(etToolID, s -> requestForTool());

        initEdit(etLotID, s -> requestForTool());

        initEdit(etEqpWorkID, new editTextListener() {
            @Override
            public void onTextChangeListener(String s) {

                FreeUI_EntityCallBack<BaseResponseBean<EqpInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EqpInfoEntity>>
                        ("正在查询设备信息", new TypeToken<BaseResponseBean<EqpInfoEntity>>() {
                        }.getType(), getSupportFragmentManager(), ToolBindActivity.this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<EqpInfoEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(ToolBindActivity.this, true, getSupportFragmentManager())) {
                            if (response.body().getResponse().getBody().getEQUIPMENT() != null){
                                EqpInfoEntity.EqpInfo equipment = response.body().getResponse().getBody().getEQUIPMENT();
                                tvEqpWorkPosition.setText(equipment.getLOCATION());

                                // 如果设备不是空闲状态的(IDLE)，查询一下设备上面是否有在运行的批次
                                // XXX 901713 多设备作业的时候，调用这个接口可能会查询不到批次
                                // 原因是后台使用方法 lotManage.getRunningLotsByEqp处理得不够好
                                // 这个在后台修改能够解决，替换成完善好的方法 breManage.getRunningLotsByEqp能够处理
                                if (StringUtils.equals("IDLE", equipment.getSTATE())) {
                                    // 扫入的设备是空闲状态，但是之前查询的设备是有批次并赋值了变量 eqpRunningLot
                                    // 需要相关信息清空，防止重复请求治具信息
                                    if (StringUtils.isNotEmpty(eqpRunningLot)) {
                                        eqpRunningLot = null;
                                        etLotID.setText(StringUtils.EMPTY);
                                    }
                                } else {
                                    // 设备不是空闲的状态，查询设备上是否有运行的批次，校验治具会使用其来校验
                                    searchRunningLotByEqp();
                                }
                            }
                            requestPositionList(s);
                            // 触发点：计划扫描治具编号、设备编号和批次id都会触发查询治具信息
                            requestForTool();
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<EqpInfoEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"EQPQUARY");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "EQPBYID");
                EquipMentEntity equipMentEntity = new EquipMentEntity();
                equipMentEntity.setEQUIPMENTID(s);
                map.add("EQUIPMENT", new JsonParser().parse(new Gson().toJson(equipMentEntity)).getAsJsonObject());
                NetUtils.requestPostNet("IF.BREQUERYEQP", "Common", ToolBindActivity.this, map, callBack);

            }
        });
    }

    /**
     * 查询设备上正在运行的批次，由于后台逻辑是以其来校验治具BOM的（如果治具需要批次辅助校验的话）
     * 这里提前进行请求，提示操作员，防止操作员看到治具BOM校验失败忘记这一原因
     */
    private void searchRunningLotByEqp() {

        if (StringUtils.isEmpty(getText(etEqpWorkID))) {
            return;
        }

        // 如果之前有查到过设备上运行的批次，在执行查找之前清空掉输入框的信息
        // 因为系统原因设备不是空闲状态，后台逻辑有可能找不到
        if (StringUtils.isNotEmpty(eqpRunningLot)) {
            etLotID.setText(StringUtils.EMPTY);
        }

        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                ("正在查询批次信息", new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), ToolBindActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(ToolBindActivity.this, true, getSupportFragmentManager(), false)) {
                    List<LotInfoEntity.LotBean> lotList = response.body().getResponse().getBody().getLOTLIST();
                    if (lotList != null && lotList.size() > 0){
                        showToast("设备上有运行的批次", true);
                        etLotID.setText(lotList.get(0).getLOTID());
                        // 找到设备上有运行的批次，将其赋值给变量，后续重复查询时设备时，可通过变量即使清空批次输入框信息，避免重复请求查询治具接口
                        eqpRunningLot = lotList.get(0).getLOTID();
                        return;
                    }
                    // 没有找到设备上运行的批次，将变量值eqpRunningLot赋值为空，防止后续程序自动请求治具信息
                    eqpRunningLot = null;
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"EQPRUNNINGLOTQUARY");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "LOTLISTRUNBYEQP");
        map.addProperty("EQUIPMENTID", getText(etEqpWorkID));
        NetUtils.requestPostNet("IF.LOTQUERY", "Common", ToolBindActivity.this, map, callBack);

    }

    private void requestPositionList(String s) {
        FreeUI_EntityCallBack<BaseResponseBean<List<String>>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<List<String>>>
                (new TypeToken<BaseResponseBean<List<String>>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<List<String>>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    mPositionList.clear();
                    if (response.body().getResponse().getBody() == null) {
                        return;
                    }

                    mPositionList.addAll(response.body().getResponse().getBody());

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<List<String>>> response) {
                super.onError(response);
                loadError(response.getException(),"GetStationByEqpId");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",s);
        NetUtils.requestPostNet("GetStationByEqpId","GetStationByEqpId",ToolBindActivity.this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit,R.id.flPositionList})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit21")){
//                    return;
//                }

                if (getText(etEqpWorkID).equals("") || getText(etToolID).equals("")){
                    showToast("设备号或ToolID不能为空",false);
                    return;
                }

                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
                    @Override
                    public void onSuccess() {
                        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                                (new TypeToken<BaseResponseBean<JSONObject>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                                    qcInfo();
//                                    showToast("绑定成功",true);
//                                    finish();
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                                super.onError(response);
                                loadError(response.getException(),"TOOLREPORT");
                            }
                        };
//                        JsonObject map = new JsonObject();
//                        map.addProperty("ACTIONTYPE","UP");
//                        map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
//                        map.addProperty("LOTID",getText(etLotID));
//                        map.addProperty("SITE",tvPosition.getText().toString());
//                        List<ToolEntity> toolList = new ArrayList<>();
//                        ToolEntity toolEntity = new ToolEntity(getText(etToolID));
//                        toolList.add(toolEntity);
//                        map.add("TOOLLIST",new JsonParser().parse(new Gson().toJson(toolList)).getAsJsonArray());
//                        NetUtils.requestPostNet("IF.TOOLREPORT","TOOLREPORT",ToolBindActivity.this,map,callBack);
                        JsonObject map = new JsonObject();
                        map.addProperty("ACTIONTYPE","UP");
                        map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
                        map.addProperty("LOTID",getText(etLotID));
                        map.addProperty("SITE",tvPosition.getText().toString());
                        List<ToolEntity> toolList = new ArrayList<>();
                        ToolEntity toolEntity = new ToolEntity(getText(etToolID));
                        toolList.add(toolEntity);
                        map.add("TOOLLIST",new JsonParser().parse(new Gson().toJson(toolList)).getAsJsonArray());
                        NetUtils.requestPostNet("CPC.TOOLREPORT","TOOLREPORT",ToolBindActivity.this,map,callBack);
                    }
                }, () -> {

                }).show(getSupportFragmentManager(),"TOOLREPORT");
                break;
            case R.id.flPositionList:

                if (mPositionList.size() <= 0){
                    showToast("未获取到站点列表",false);
                    return;
                }

                if (mPositionPop != null) {
                    if (mPositionPop.isShowing()) {
                        mPositionPop.dismiss();
                    }
                } else {
                    mPositionPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPositionList.getWidth(), mPositionList, ivPositionArrow, (codeS, i) -> {
                        tvPosition.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivPositionArrow);
                mPositionPop.showAsDropDown(flPositionList, 0, 0);
                break;
        }

    }


    private void qcInfo(){

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    showToast("绑定成功",true);
                    finish();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"TOOLCHANGE");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("EQUIPMENTID",getText(etEqpWorkID));
        map.addProperty("TOOLID",getText(etToolID));
        map.addProperty("LOTID",getText(etLotID));
        map.addProperty("TRANSTYPE","ON");
        NetUtils.requestPostNet("IF.TOOLCHANGE","Common",ToolBindActivity.this,map,callBack);

    }



    private void requestForTool() {
        // 前置校验，必须要有tool id和批次号才可以进行请求
        // 治具编号、设备编号、治具号不为空的情况下，前置校验通过，可以进行请求
        if (StringUtils.isAnyEmpty(etLotID.getText(), etEqpWorkID.getText(), etToolID.getText())) {
            return;
        }

        // 校验通过 则进行请求转发
        FreeUI_EntityCallBack<BaseResponseBean<ToolEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<ToolEntity>>
                (new TypeToken<BaseResponseBean<ToolEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<ToolEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    // 请求治具数据成功，可以获取到治具的相关信息，进行信息的渲染
                    ToolEntity toolEntity = response.body().getResponse().getBody().getXTool();
                    if (validateToolLimitLife(toolEntity)) {
                        tvToolLimitLife.setText(toolEntity.getLIMITLIFE());
                        tvToolCurrentCount.setText(toolEntity.getCURRENTCOUNT());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<ToolEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"FINDMLOTBYID");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "QUERYBYID");
        map.addProperty("MLOTID", String.valueOf(etToolID.getText()));
        map.addProperty("EQUIPMENTID", String.valueOf(etEqpWorkID.getText()));
        map.addProperty("LOTID", String.valueOf(etLotID.getText()));
        NetUtils.requestPostNet("IF.FINDMLOTBYID", "Common", ToolBindActivity.this, map, callBack);

    }

    private boolean validateToolLimitLife(ToolEntity toolEntity) {
        try {
            // 如果当前寿命、当前使用次数为空，或者它有数据但是数据校验不通过的
            // 两个字段的寿命如果是小于等于-1的话就认为数据是有问题的
            final BigDecimal MINUS_ONE = new BigDecimal("-1");
            return StringUtils.isNotEmpty(toolEntity.getLIMITLIFE())
                    && BigDecimal.valueOf(Long.parseLong(toolEntity.getLIMITLIFE())).compareTo(MINUS_ONE) > 0
                    && StringUtils.isNotEmpty(toolEntity.getCURRENTCOUNT())
                    && BigDecimal.valueOf(Long.parseLong(toolEntity.getCURRENTCOUNT())).compareTo(MINUS_ONE) > 0;
        } catch (Exception e) {
            FreeApi_LogUtils.saveErrorMessages(e, e.getMessage());
            return false;
        }
    }
}
